import os
import cv2
import json
import easyocr
import tempfile
import pytesseract
from PIL import Image


def get_coordinates(image, model, confidence_threshold=0.75, iou_threshold=0.45):
    im = cv2.imread(image)[..., ::-1]
    model.conf = confidence_threshold
    model.iou = iou_threshold
    coordinates = model(im)
    return coordinates.pandas().xyxy[0]


def extract_text_from_crops(crops, class_info, model_flag='tesseract'):
    extracted_text = []
    for i, crop in enumerate(crops):
        if model_flag == 'tesseract':
            text = pytesseract.image_to_string(
                crop, config='--psm 6', lang='rus')
        elif model_flag == 'easyocr':
            with tempfile.NamedTemporaryFile(suffix='.png', delete=False) as temp_file:
                pil_image = Image.fromarray(crop)
                pil_image.save(temp_file.name)
            reader = easyocr.Reader(['ru', 'en'])
            results_easyocr = reader.readtext(temp_file.name, detail=0)
            text = results_easyocr[0] if results_easyocr else ''
            os.remove(temp_file.name)

        result_info = {
            'class': class_info[i],
            'text': text,
        }
        extracted_text.append(result_info)
    return extracted_text


def save_text(text_data, output_path):
    with open(output_path, 'w') as json_file:
        json.dump(text_data, json_file, ensure_ascii=False, indent=4)
